// pages/coupon/index.js
const {getCouponList} = require('../../api/coupon');
Page({
  data: {
    active: 0,
    couponList: [],
    currentPage: 1,
    pageSize: 10,
    finished: false,
    isEmpty: false,
    loading: true,
    tabs: [
      { title: '可用', status: 0 },
      { title: '已使用', status: 1 },
      { title: '已过期', status: 2 },
      { title: '不可用', status: 3 }
    ],
    currentStatus: 0
  },

  onLoad: function (options) {
    // 如果从其他页面跳转过来并指定了状态，则切换到对应标签
    if (options.status) {
      const index = this.data.tabs.findIndex(tab => tab.status === options.status);
      if (index !== -1) {
        this.setData({ active: index, currentStatus: options.status });
      }
    }
    
    // 如果是从选择优惠券页面跳转过来的，设置选择模式
    if (options.select) {
      this.setData({
        isSelectMode: options.select === 'true'
      });
    }
    
    this.loadCouponList();
  },

  onPullDownRefresh: function () {
    this.resetAndReload();
    wx.stopPullDownRefresh();
  },

  // 切换标签
  onTabChange: function (event) {
    const index = event.detail.index;
    const status = this.data.tabs[index].status;
    
    this.setData({
      active: index,
      currentStatus: status,
      currentPage: 1,
      couponList: [],
      loading: true,
      isEmpty: false
    });
    
    this.loadCouponList();
  },

  // 加载优惠券列表
  loadCouponList: function () {
    const { currentPage, pageSize, couponList, currentStatus } = this.data;
    
    // 显示加载状态
    this.setData({ loading: true });

    getCouponList({
      current: currentPage,
      pageSize: pageSize,
      status: currentStatus
    }).then(res => {
      console.log(currentStatus);
      console.log(res);
      if(res.code == 20000){      
        console.log(res.list);
        this.setData({
          couponList: [...couponList, ...res.list],
          loading: false,
          isEmpty: currentPage === 1 && res.list.length === 0,
          finished: res.list.length < pageSize,
          currentPage: currentPage + 1
        });
      }else {
        wx.showToast({
          title: res.msg || '优惠券列表加载失败',
          icon: 'none'
        });
      }
     }).catch(err => {
      console.error('优惠券列表加载失败:', err);
      wx.showToast({
        title: '优惠券列表加载失败',
        icon: 'none'
      });
    })
  },

  // 重置并重新加载
  resetAndReload: function () {
    this.setData({
      couponList: [],
      loading: true,
      isEmpty: false,
      currentPage: 1,
      finished: false,
    });
    console.log("now i am at reset!")
    this.loadCouponList();
  },

  // 使用优惠券
  useCoupon: function (event) {
    const couponId = event.currentTarget.dataset.id;
    // 如果是选择模式，则返回选中的优惠券
    if (this.data.isSelectMode) {
      const selectedCoupon = this.data.couponList.find(item => item.id === couponId);
      
      if (selectedCoupon) {
        // 将选中的优惠券信息返回给上一页
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        
        // 调用上一个页面的方法，传递选中的优惠券
        if (prevPage && prevPage.setSelectedCoupon) {
          prevPage.setSelectedCoupon(selectedCoupon);
        }
        
        wx.navigateBack();
      }
      return;
    }
    
    // 非选择模式，跳转到商品列表页面
    console.log("coupon id:")
    console.log(couponId)
    wx.navigateTo({
      url: '/pages/index/index?couponId=' + couponId
    });
  },


  // 格式化日期
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    
    return `${year}.${month}.${day}`;
  }
});